package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-16 22:12
 **/
public class LeetCode707 {

    //伪头结点
    Node head;
    //节点的长度
    int len;

    public LeetCode707() {
        head = new Node();
    }

    public int get(int index) {
        if (index >= len) {
            return -1;
        }
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp.next.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(len,val);
    }

    public void addAtIndex(int index, int val) {
        if (index < 0) {
            index = 0;
        }
        if (index > len) {
            return;
        }
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }

        Node add = new Node(val, temp.next);
        temp.next = add;
        len++;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= len) {
            return;
        }
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        len--;
    }

    public static void main(String[] args) {
        LeetCode707 code = new LeetCode707();
        /*code.addAtHead(1);
        code.addAtTail(3);
        code.addAtIndex(1,2);
        System.out.println(code.get(1));
        code.deleteAtIndex(1);
        System.out.println("code.get(1) = " + code.get(1));*/

        code.addAtHead(5);
        code.addAtIndex(1,2);
        System.out.println("code.get(1) = " + code.get(1));
        code.addAtHead(6);
        code.addAtTail(2);
        System.out.println("code.get(3) = " + code.get(3));
        code.addAtTail(1);
        System.out.println("code.get(5) = " + code.get(5));
        code.addAtHead(2);
        System.out.println("code.get(2) = " + code.get(2));
        code.addAtHead(6);
    }
}

class Node {
    int val;
    Node next;
    Node(){}
    Node(int val,Node next){
        this.val = val;
        this.next = next;
    }
}
